const sql = require("./db");

const Tutorial = function(tutorial){
    this.title = tutorial.title;
    this.description = tutorial.description;
    this.published = tutorial.published;
};

Tutorial.save = (newTutorial,result) =>{
    let query = "insert into tutorials set ?";
    sql.query(query,newTutorial,(err,data) =>{
        if(err){
            console.error(err);
            result(err,null);
            return;
        }
        console.log("created tutorial: ",{id:data.insertId,...newTutorial});
        result(null,{id:data.insertId,...newTutorial});
    })
}
Tutorial.getAll = (title,result) =>{
    let query = "select * from tutorials";
    if(title){
        query += ` where title like '%${title}%'`;
    }
    sql.query(query,(err,data) =>{
        if(err){
            console.log("error",err);
            result(null,err);
        }
        console.log("Tutorials:",data);
        result(null,data);
    })
};

Tutorial.getById = (id,result) =>{
    let query = `select * from tutorials where id = ${id}`;
    sql.query(query,(err,data) =>{
        if(err){
            console.log("err",err);
            result(err,null);
            return;
        }
        if(data.length){
            console.log(`found tutorial: ${data[0]}`);
            result(null,data[0]);
            return;
        }
        result({kind:"not_found"},null);
    })
};

Tutorial.getAllPublished = (result) =>{
    let query = "select * from tutorials where published = true";
    sql.query(query,(err,data) =>{
        if(err){
            console.log("err",err);
            result(err,null);
            return;
        }
        result(null,data);
    })
};

Tutorial.updateById = (id,tutorial,result) =>{
    let query = "update tutorials set title = ?,description = ?,published = ? where id = ?";
    sql.query(query,[tutorial.title,tutorial.description,tutorial.published,id],(err,data) =>{
        if(err){
            console.log("error",err);
            result(err,null);
            return;
        };
        if(data.affectedRows == 0){
            result({kind:"not_found"},null);
            return;
        }
        console.log("updated tutorial: ",{id:id,...tutorial});
        result(null,{id:id,...tutorial});
    })
};

Tutorial.removeById = (id,result) =>{
    let query = `delete from tutorials where id = ?`;
    sql.query(query,[id],(err,data) =>{
        if(err){
            console.log(err);
            result(err,null);
            return;
        }else{
            console.log(`remove successfully by id:${id}`);
            result(null,data);
        }
    })
}

module.exports = Tutorial;